<template>
	<div class="main">
		<div class="btn"  @click="oauthLogin">点击授权</div>
	</div>
</template>
<script>
	//引入js
	import router from '@/router/index'
	import { loginByOpenid } from '@/api/student'

	export default {
		components: {
			
		},
		data() {
			return {
				baseUrl:process.env.VUE_APP_BASE_API,
				appId:'',
				url: ''
			}
		},
		created: function() {
			//获取appid
			this.appId=this.$store.state.globalData.wechatConfig.appId
			//获取url地址
			this.url = window.location.href;
			//获取code
			var code=this.getQueryString("code");
			//code不存在则开始授权处理
			if(!code)
			{
				return
			}
			//取得code，ajax获取用户信息并实现注册登录
			this.login(code,this.url);
		},
		beforeMount: function() {
			
		},
		mounted: function() {
			
		},
		methods: {
			// 获取地址栏参数
			getQueryString(name) {
				let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
				let url = window.location.search.substr(1).match(reg);
				return url ? decodeURI(url[2]) : null;
			},
			oauthLogin: function(){
				window.location="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+this.appId+"&redirect_uri="+encodeURIComponent(this.url)+"&response_type=code&scope=snsapi_userinfo#wechat_redirect";
			},
			login:async function(code,url){
				//拿到token
				var ajaxData={}
				ajaxData.code=code
				var resultData=await loginByOpenid(ajaxData);
				
				if(resultData.code==200)
				{
					//存起来token和身份信息
					var expireTime=Date.parse(new Date())/1000+72000;//20小时后过期
					//同步更新store
					this.$store.commit("setIdentity",1);
					this.$store.commit("setToken",resultData.data);
					this.$store.commit("setExpireTime",expireTime);
					 /*存储到ls*/
					localStorage.setItem('identity',1);
					localStorage.setItem('token',resultData.data);
					localStorage.setItem('expireTime',expireTime);
					
					//跳转到指定页面
					url=url.split('?')[2];
					if(!url){
						router.replace({path:"/wechatstudent/loading"});
						return 0;
					}
					var action=url.split('&')[0];
					if(!action){
						router.replace({path:"/wechatstudent/loading"});
						return 0;
					}
					action=action.replace('action=','');
					router.replace({path:action});
					return 0;
				}
			}
		}
	}
</script>
<style lang="scss" scoped>
	.main{
		width: 100%;
		overflow: hidden;
		.btn{
			margin-left: 20px;
			margin-right: 20px;
			margin-top: 50px;
			margin-bottom: 50px;
			background-color: #0095ff;
			color: #ffffff;
			line-height: 50px;
			border-radius: 6px;
			text-align: center;
		}
	}
</style>
